<?php

namespace App\Models;

use App\Models\Traits\BelongsToApplication;
use App\Models\Traits\HasCovers;
use App\Models\Traits\HasEasyStatus;
use Exception;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;

class Sponsor extends Model implements Sortable
{
    use BelongsToApplication,
        Cachable,
        HasEasyStatus,
        HasCovers,
        SortableTrait,
        SoftDeletes;

    protected array $sortable = [
        'order_column_name' => 'order',
        'sort_when_creating' => true,
    ];

    protected static function boot(): void
    {
        parent::boot();

        self::creating(function (Sponsor $model) {
            if (!$model->chapter) {
                throw new Exception('缺少选手场次');
            }

            $model->season_id = $model->chapter->season_id;
        });
    }

    public function buildSortQuery(): Builder
    {
        return static::query()
            ->where('application_id', $this->application_id)
            ->where('season_id', $this->season_id)
            ->where('chapter_id', $this->chapter_id);
    }

    public function season(): BelongsTo
    {
        return $this->belongsTo(Season::class);
    }

    public function chapter(): BelongsTo
    {
        return $this->belongsTo(Chapter::class);
    }
}
